package com.xinzhidi.web.ctw.service;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.xinzhidi.common.constant.AgreementConstants;
import com.xinzhidi.web.alarmSetting.domain.AlarmSetting;
import com.xinzhidi.web.alarmSetting.service.AlarmSettingService;
import com.xinzhidi.web.ctw.domain.entity.HouseholdTemperature;
import com.xinzhidi.web.ctw.domain.po.TemperaturePo;
import com.xinzhidi.web.ctw.mapper.HouseholdTemperatureMapper;
import com.xinzhidi.web.equipment.domain.Equipment;
import com.xinzhidi.web.equipmentAlarm.domain.EquipmentAlarm;
import com.xinzhidi.web.equipmentAlarm.service.EquipmentAlarmService;
import com.xinzhidi.web.house.service.IHouseholdService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.math.BigDecimal;


/**
 * 室温-（实时数据）Service业务层处理
 *
 * @author cx
 * @date 2023-05-29
 */
@Service
public class HouseholdTemperatureService extends ServiceImpl<HouseholdTemperatureMapper, HouseholdTemperature> {


    @Autowired
    private IHouseholdService householdService;

    @Autowired
    private CtwService ctwService;

    @Autowired
    private AlarmSettingService alarmSettingService;

    @Autowired
    private EquipmentAlarmService equipmentAlarmService;

    /**
     * 根据条件获取平均室温
     *
     * @param po 室温po
     * @return 室温
     */
    public BigDecimal getAvgTemperature(TemperaturePo po) {
        return baseMapper.getAvgTemperature(po);
    }

    /**
     * 检查是否超限异常及波动异常
     *
     * @param equipment          设备
     * @param oldTrueTemperature 原室温
     * @param trueTemperature    当前室温
     * @return
     */
    public void checkTransfiniteException(Equipment equipment, BigDecimal oldTrueTemperature, BigDecimal trueTemperature) {
        if (oldTrueTemperature == null) {
            return;
        }
        LambdaQueryWrapper<AlarmSetting> wrapper = Wrappers.lambdaQuery();
        wrapper.eq(AlarmSetting::getAlarmType, AgreementConstants.ExceptionType.TRANSFINITE_EXCEPTION);
        wrapper.eq(AlarmSetting::getIndexType, AgreementConstants.ControlTactics.ROOM_TEMPERATURE);
        AlarmSetting setting = alarmSettingService.getOne(wrapper);

        EquipmentAlarm alarm;
        LambdaQueryWrapper<EquipmentAlarm> alarmWrapper;
        if (setting != null) {
            BigDecimal maxValue = setting.getMaxValue();
            BigDecimal minValue = setting.getMinValue();
            if (trueTemperature.compareTo(maxValue) > 0 || trueTemperature.compareTo(minValue) < 0) {
                //超限异常
                //如果之前有该设备的超限异常且未处理，则不再记录
                alarmWrapper = Wrappers.lambdaQuery();
                alarmWrapper.eq(EquipmentAlarm::getEquipmentId, equipment.getId())
                        .eq(EquipmentAlarm::getAlarmSettingId, setting.getId())
                        .eq(EquipmentAlarm::getStatus, "0");
                alarm = equipmentAlarmService.getOne(alarmWrapper);
                if (alarm == null) {
                    alarm = new EquipmentAlarm();
                    alarm.setPlotId(equipment.getLotId());
                    alarm.setBuildId(equipment.getBuildId());
                    alarm.setUnitId(equipment.getUnitId());
                    alarm.setHouseholdId(equipment.getHouseholdId());
                    alarm.setEquipmentId(equipment.getId());
                    alarm.setAlarmSettingId(setting.getId());
                    alarm.setHideOrPush(Integer.parseInt(setting.getPushStatus()));
                    alarm.setPushNum(setting.getPushInterval());
                    alarm.setRemark("设备【" + equipment.getEquipmentName() + "】室内温度超限异常");
                    equipmentAlarmService.save(alarm);
                }
            }
        }

        wrapper.clear();
        wrapper.eq(AlarmSetting::getAlarmType, AgreementConstants.ExceptionType.UNDULATE_EXCEPTION);
        wrapper.eq(AlarmSetting::getEquipmentType, AgreementConstants.ControlTactics.ROOM_TEMPERATURE);
        setting = alarmSettingService.getOne(wrapper);
        if (setting == null) {
            return;
        }
        //波动值
        BigDecimal fluctuatingValue = setting.getFluctuatingValue();
        BigDecimal maxFluctuatingValue = oldTrueTemperature.add(fluctuatingValue);
        BigDecimal minFluctuatingValue = oldTrueTemperature.subtract(fluctuatingValue);
        if (trueTemperature.compareTo(maxFluctuatingValue) <= 0 && trueTemperature.compareTo(minFluctuatingValue) >= 0) {
            return;
        }
        //判断之前该室温采集器有无波动异常且未处理的告警信息，如果有则不再新增
        alarmWrapper = Wrappers.lambdaQuery();
        alarmWrapper.eq(EquipmentAlarm::getEquipmentId, equipment.getId())
                .eq(EquipmentAlarm::getAlarmSettingId, setting.getId())
                .eq(EquipmentAlarm::getStatus, "0");
        alarm = equipmentAlarmService.getOne(alarmWrapper);
        if(alarm == null){
            return;
        }
        alarm = new EquipmentAlarm();
        alarm.setPlotId(equipment.getLotId());
        alarm.setBuildId(equipment.getBuildId());
        alarm.setUnitId(equipment.getUnitId());
        alarm.setHouseholdId(equipment.getHouseholdId());
        alarm.setEquipmentId(equipment.getId());
        alarm.setAlarmSettingId(setting.getId());
        alarm.setHideOrPush(Integer.parseInt(setting.getPushStatus()));
        alarm.setPushNum(setting.getPushInterval());
        alarm.setRemark("设备【" + equipment.getEquipmentName() + "】室内温度超限异常");
        equipmentAlarmService.save(alarm);
    }

//    /**
//     * 根据住户id获取室温
//     *
//     * @param householdId 住户id
//     * @return 室温
//     */
//    public HouseholdTemperature getTemperatureByHouseholdId(Long householdId) {
//        BigDecimal temperature;
//        BigDecimal modifiedTemperature;
//        BigDecimal setTemperature;
//        Integer signalStrength;
//        //根据住户id获取住户信息
//        Household household = householdService.getById(householdId);
//        //根据住户信息获取设备id
//        String deviceId = household.getDeviceId();
//        if(StringUtils.isBlank(deviceId)){
//            throw new ServiceException("该住户未绑定室温采集器设备");
//        }
//        //根据设备id获取室温
//        BodyResponse response = ctwService.getRoomTemperature(deviceId);
//        HouseholdTemperature householdTemperature = null;
//        if (response.getCode() == 0) {
//            temperature = response.getDeviceStatus().getTrueTemperature();
//            modifiedTemperature = response.getDeviceStatus().getModifiedTemperature();
//            setTemperature = response.getDeviceStatus().getSetTemperature();
//            signalStrength = response.getDeviceStatus().getSignalStrength();
//            //修改住户室温实时数据
//            LambdaQueryWrapper<HouseholdTemperature> wrapper = Wrappers.lambdaQuery();
//            wrapper.eq(HouseholdTemperature::getHouseholdId, householdId);
//            householdTemperature = this.getOne(wrapper);
//            if(householdTemperature == null){
//                householdTemperature = new HouseholdTemperature();
//                householdTemperature.setPlotId(household.getPlotId());
//                householdTemperature.setBuildId(household.getBuildId());
//                householdTemperature.setUnitId(household.getUnit());
//                householdTemperature.setHouseholdId(householdId);
//                householdTemperature.setDeviceId(deviceId);
//                householdTemperature.setTemperature(temperature);
//                householdTemperature.setModifiedTemperature(modifiedTemperature);
//                householdTemperature.setSetTemperature(setTemperature);
//                householdTemperature.setSignalStrength(signalStrength);
//                householdTemperature.setReportTime(response.getDeviceStatus().getTime());
//                this.save(householdTemperature);
//            }else{
//                householdTemperature.setTemperature(temperature);
//                householdTemperature.setReportTime(response.getDeviceStatus().getTime());
//                this.updateById(householdTemperature);
//            }
//        }
//
//        return householdTemperature;
//    }


}
